import axios, {
  AxiosInstance,
  AxiosError,
  AxiosResponse,
  AxiosRequestConfig,
  AxiosRequestHeaders,
} from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/user";
const service: AxiosInstance = axios.create({
  baseURL: `${import.meta.env.VITE_BASE_API}`,
  timeout: 30000,
});

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const userStore = useUserStore();
    const headers = config.headers as AxiosRequestHeaders;
    headers["authorization"] = `Bearer ${userStore.token}`;
    return config;
  },
  (error: AxiosError) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      const data = response.data;
      if (data.code !== 0) {
        ElMessage.error(data.msg || "操作失败");
        return Promise.reject(data);
      }
      return data.data;
    } else {
      Promise.reject();
    }
  },
  (error: AxiosError) => {
    console.log(error);
    ElMessage({
      showClose: true,
      message: error.message,
      type: "error",
    });
    return Promise.reject();
  }
);

export default service;
